﻿using UnityEngine;
using System.Collections;

public class Scroll : MonoBehaviour {

    public Transform container;
    public Renderer platform;

    private Material m_platformMat; //平台的贴图.
    private float m_platformTextureSpeed; //平台贴图移动的速度.

    private Vector3 m_mousePos=Vector3.zero;
    private float m_deltaX=0f;
    private bool m_isDown = false;

	// Use this for initialization
	void Start () {
        if (platform)
        {
            m_platformMat = platform.sharedMaterial;
            if (m_platformMat)
            {
                m_platformMat.SetTextureOffset("_MainTex", Vector2.zero);
                m_platformTextureSpeed = m_platformMat.GetTextureScale("_MainTex").x / platform.transform.localScale.x;
            }
        }
	}
	
	// Update is called once per frame
	void Update () {
        if (!m_isDown)
        {
            m_deltaX = Mathf.Lerp(m_deltaX, 0f, 0.2f);
        }
        if (Mathf.Abs(m_deltaX) > 0.02f)
        {
            if (container)
            {
                container.Translate(m_deltaX, 0f, 0f);
            }
            if (m_platformMat)
            {
                Vector2 offset = m_platformMat.GetTextureOffset("_MainTex");
                offset.x -= m_deltaX * m_platformTextureSpeed;
                m_platformMat.SetTextureOffset("_MainTex", offset);
            }
        }
	}

    void OnMouseDown()
    {
        m_isDown = true;
        Vector3 pos = Input.mousePosition;
        pos.z = Camera.main.transform.position.z;
        m_mousePos = Camera.main.ScreenToWorldPoint(pos);
    }

    void OnMouseDrag()
    {
        Vector3 pos = Input.mousePosition;
        pos.z = Camera.main.transform.position.z;
        Vector3 tempPos = Camera.main.ScreenToWorldPoint(pos);

        m_deltaX = (m_mousePos - tempPos ).x;
        m_mousePos = tempPos;
    }

    void OnMouseUp()
    {
        m_isDown = false;
    }
}
